package com.zink.ezequiel.codes;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.View;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockExpandableListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.desandroid.framework.ada.exceptions.AdaFrameworkException;
import com.zink.ezequiel.codes.adapter.TagsAdapter;
import com.zink.ezequiel.codes.data.ApplicationDataContext;
import com.zink.ezequiel.codes.data.model.Entry;
import com.zink.ezequiel.codes.data.model.Tag;

import java.util.ArrayList;
import java.util.List;

public class TagsActivity extends SherlockExpandableListActivity {

    /**
     * TAG to identify log message from that Class.
     */
    private static final String TAG = "TagsActivity";
	private static final int CONTEXT_MENU_VIEW_ITEM = Menu.FIRST;
	private static final int CONTEXT_MENU_EDIT = Menu.FIRST+1;
	private static final int CONTEXT_MENU_DELETE = Menu.FIRST+2;
    /**
     * Persistence object manager.
     */
    private ApplicationDataContext dataContext;
 
    //private ArrayAdapter<Entry> codeListAdapter;

    private TagsAdapter tagsListAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        tagsListAdapter = new TagsAdapter(this, R.layout.codes_list_item,  R.layout.codes_list_item);
        try {
            dataContext = new ApplicationDataContext(this);

            // Check if song list have already been loaded
            if (!dataContext.isSongListLoaded()) {
                initializeDatabase();
            } else {
                populateTagsContent();
            }
            setListAdapter(tagsListAdapter);
        } catch (Exception e) {
            Log.e(TAG, "Exception was caught creating ApplicationDataContext", e);
            Toast.makeText(this, "Error loading tags list", Toast.LENGTH_SHORT).show();
        }
        //registerForContextMenu(this.getExpandableListView());
    }
    
    private void populateTagsContent() throws AdaFrameworkException {
    	dataContext.getTagsSet().fill();
    	ArrayList<String> groups = new ArrayList<String>();
    	ArrayList<ArrayList<Entry>> childrens = new ArrayList<ArrayList<Entry>>();
    	
    	dataContext.getEntriesSet().fill();
    	for (Tag tag: dataContext.getTagsSet()){
    		groups.add(tag.getTagName());
    		ArrayList<Entry> childs = new ArrayList<Entry>();
    		for (Entry entry: dataContext.getEntriesSet()){
    			if(tag.getID() == entry.getTag().getID()) {
    				childs.add(entry);
    			}
    		}
    		childrens.add(childs);
    	}
    	this.tagsListAdapter.setData(groups, childrens);
	}

	@Override
    protected void onResume() {
        Log.i(TAG, "onResume");
        try {
        	populateTagsContent();
        } catch (Exception e) {
            Log.e(TAG, "Exception was caught loading list", e);
            Toast.makeText(this, "Error loading song list", Toast.LENGTH_SHORT).show();
        }
        tagsListAdapter.notifyDataSetChanged();
        this.getExpandableListView().invalidate();
        super.onResume();
    }
    private void initializeDatabase() throws Exception {
        List<Tag> tags = new ArrayList<Tag>();
        tags.add(new Tag("Green Day"));

        dataContext.getTagsSet().addAll(tags);
        dataContext.getTagsSet().save();
    	
        List<Entry> aux = new ArrayList<Entry>();
        aux.add(new Entry("ebay", "user23", "password",
    			"http://saraza.com", "This is a single nite",tags.get(0)));
        aux.add(new Entry("ebay2", "user23", "password",
    			"http://saraza.com", "This is a single nite", tags.get(0)));
        aux.add(new Entry("ebay2", "user23", "password",
    			"http://saraza.com", "This is a single nite", tags.get(0)));
        dataContext.getEntriesSet().addAll(aux);
        dataContext.getEntriesSet().save();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = this.getSupportMenuInflater();
        inflater.inflate(R.menu.activity_codes , menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_new:
            	newEntryAction();
                return true;
            case R.id.menu_update:
            	onResume();
                Toast.makeText(this, "Code list updated", Toast.LENGTH_SHORT).show();
            	return true;
            case R.id.menu_lock:
                //showHelp();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
    	menu.add(Menu.NONE, CONTEXT_MENU_VIEW_ITEM, Menu.NONE, "View");
    	menu.add(Menu.NONE, CONTEXT_MENU_EDIT, Menu.NONE, "Edit");
    	menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "Delete");

    }


    private void newEntryAction() {
        Intent intent = new Intent(this, CodeDetailsActivity.class);
        intent.putExtra(CodeDetailsActivity.PARCEL_ENTRY_MODE, CodeDetailsActivity.NEW_MODE);
        startActivity(intent);		
	} 
    
    private void viewEntryAction(long entryId) {
        Intent intent = new Intent(this, CodeDetailsActivity.class);
        intent.putExtra(CodeDetailsActivity.PARCEL_ENTRY_ID, entryId);
        intent.putExtra(CodeDetailsActivity.PARCEL_ENTRY_MODE, CodeDetailsActivity.VIEW_MODE);
        startActivity(intent);	
	} 
    
    private void editEntryAction(long entryId) {
        Intent intent = new Intent(this, CodeDetailsActivity.class);
        intent.putExtra(CodeDetailsActivity.PARCEL_ENTRY_ID, entryId);
        intent.putExtra(CodeDetailsActivity.PARCEL_ENTRY_MODE, CodeDetailsActivity.EDIT_MODE);
        startActivity(intent);
	} 
 
    private void deleteEntryAction(long entryId) {
	
	}
    
	private void copyPaste() {
    	int sdk = android.os.Build.VERSION.SDK_INT;
//    	if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
//    	    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
//    	    clipboard.setText("text to clip");
//    	} else {
//    	    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
//    	    android.content.ClipData clip = android.content.ClipData.newPlainText("text label","text to clip");
//    	    clipboard.setPrimaryClip(clip);
//    	}
    }
}
